/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

//第一种解法:使用差值法,让更长的先走差值步,再一起走.
class Solution {
    ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        int lenA = 0;
        int lenB = 0;
        while(pA != null){
            lenA++;
            pA = pA.next;
        }
        while(pB != null){
            lenB++;
            pB = pB.next;
        }
        pA = headA;
        pB = headB;
        if(lenA < lenB){
            int len = lenB - lenA;
            for(int i = 0; i < len; i++){
                pB = pB.next;
            }
        }else{
            int len = lenA - lenB;
            for(int i = 0; i < len; i++){
                pA = pA.next;
            }
        }
        while(pA != null && pB != null){
            if(pA == pB) return pA;
            pA = pA.next;
            pB = pB.next;
        }
        return null;
    }
}


//第二种方法,等值法(比较简单)
class Solution {
    ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        while(pA != pB){
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}